// 添加引用
const path = require('path');
const gulp = require('gulp');
const Redis = require('ioredis');
const nodemon = require('gulp-nodemon');
const childProcess = require('child_process');
const isWindows = process.platform === 'win32';

const checkMySQLStatus = () => {
	let command = isWindows ? 'sc query wampmysqld64' : 'service wampmysqld64 status';
	return new Promise((resolve, reject) => {
		childProcess.exec(command, (error, stdout, stderr) => {
			let isRunning = false;
			if (error) {
				// 命令执行失败，可能是没有权限或命令不存在
				console.error(`执行命令失败: ${error.message}`);
				reject(new Error('无法获取MySQL状态，请检查命令权限或服务名称'));
				return;
			}
			if (stderr) {
				// 命令输出错误信息
				console.error(`命令错误输出: ${stderr}`);
				reject(new Error('执行命令时出现错误'));
				return;
			}
			// 根据不同操作系统的输出判断MySQL状态
			if (isWindows) {
				// Windows系统: 检查输出中是否包含"RUNNING"
				isRunning = stdout.includes('RUNNING');
			} else {
				// Linux系统: 检查输出中是否包含"active (running)"
				isRunning = stdout.includes('active (running)');
			}
			resolve(isRunning);
		});
	});
}

const launchServerDatabase = () => {
	let command = path.resolve('./config/script.lnk');
	return new Promise((resolve, reject) => {
		childProcess.exec(command, (error, stdout, stderr) => {
			if (error) {
				reject(new Error('无法启动MySQL服务'));
				return;
			}
			if (stderr) {
				reject(new Error('启动MySQL服务时出现错误'));
				return;
			}
			resolve(true);
		});
	});
}

//判断Redis服务是否启动
const checkRedisStatus = async () => {
	let redisClient;
	try {
		redisClient = new Redis({ host: 'localhost', port: 6379, password: '', connectTimeout: 5000 });
		await redisClient.ping();
		return true;
	} catch (error) {
		return false;
	} finally {
		redisClient && await redisClient.quit();
	}
}

const launchServerRedis = () => {
	let redisPath = 'D:\\Redis-8.2.1\\redis-server.exe';
	return new Promise((resolve, reject) => {
		let redisProcess = childProcess.spawn(redisPath);
		redisProcess.stdout.on('data', (data) => {
			const output = data.toString();
			output.includes('Ready to accept connections') && resolve(true);
		});
		redisProcess.stderr.on('data', (data) => {
			const error = data.toString();
			if (error.includes('createServer')) {
				console.error('可能原因: 端口被占用，请关闭其他Redis进程或修改配置文件中的端口');
			} else if (error.includes('The system cannot find the file specified')) {
				console.error('可能原因: Redis路径不正确，请在gulpfile.js中手动修改redisPath');
			}
			reject(false);
		});
	});
}

gulp.task("connectDatabase", async function() {
	let isRunning = await checkMySQLStatus();
	!isRunning && await launchServerDatabase();
});

gulp.task("startRedis", async function() {
	let isRunning = await checkRedisStatus();
	!isRunning && await launchServerRedis();
});

//这个可以让express启动
gulp.task("dev", function() {
	nodemon({
		script: './bin/www',
		ext: 'js html',
		env: {
			'PORT': 4000
		}
	})
});
gulp.task("start", function() {
	nodemon({
		script: './bin/www',
		ext: 'js html',
		env: {
			'PORT': 4000,
			'NODE_ENV': 'development'
		}
	})
});

gulp.task('serve', gulp.series('connectDatabase', 'startRedis', 'dev'));